package com.example.demo.util.itfcheck;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.RequestDto;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 加密解密工具
 */
public class ItfCheckUtil {
    private static final Logger logger = LoggerFactory.getLogger(ItfCheckUtil.class);

    /**
     * 接口解密
     * @param req 请求内容
     * @param prikey 接口解密私钥
     */
    public static String decryption(RequestDto req, String prikey) {
        try {
            // RSA解密获取AES原始密钥
            byte[] keyDecodeBase64 = Base64.decodeBase64(req.getKey().getBytes(Charsets.UTF_8));
            byte[] aeskey = RsaUtil.decryptByPrivateKey(keyDecodeBase64, prikey);

            // AES解密获取原始报文
            byte[] contentDecodeBase64 = Base64.decodeBase64(req.getContent().getBytes(Charsets.UTF_8));
            byte[] contentBytes = AesUtils.decrypt(contentDecodeBase64, aeskey);
            String data = new String(contentBytes, Charsets.UTF_8);
            logger.info("======返回原始报文为：" + data);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String encryption(String data, String partner, String md5key, String pubkey) {
        try {
            // AES 随机秘钥
            byte[] aesKey = AesUtils.randomKey();

            // AES加密原始报文
            byte[] contentBytes = AesUtils.encrypt(data.getBytes(Charsets.UTF_8), aesKey);
            String content = Base64.encodeBase64String(contentBytes);
            logger.info("======原始报文AES加密后为：" + content);

            // RSA加密随机秘钥
            byte[] keyBytes = RsaUtil.encryptByPublicKey(aesKey, pubkey);
            String key = Base64.encodeBase64String(keyBytes);
            logger.info("======AES密钥加密后为：" + key);

            // 数据签名（合作方标识+密文+加密后的密钥+签名密钥）
            Long timestamp = Calendar.getInstance().getTime().getTime();
            String sign = DigestUtils.md5Hex(partner + content + key + timestamp + md5key);
            logger.info("======签名后sign：" + sign);

            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("partner",partner);
            resultMap.put("key",key);
            resultMap.put("content",content);
            resultMap.put("timestamp",String.valueOf(timestamp));
            resultMap.put("sign",sign);
            return JSONObject.toJSONString(resultMap);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
